import React, { useEffect } from "react";
import DynamicRouters from "@/utils/DynamicRouters.jsx";
import { useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { Spin } from "antd";
import { findFirstPath } from "@/utils/tool.jsx";

const HomeUrl = import.meta.env.VITE_HOME_URL;
export default function Permission({ children }) {
  const navigate = useNavigate();
  const location = useLocation();
  const [isLoaded, setIsLoaded] = React.useState(false); //增状态
  let { token } = useSelector((state) => state.userStore);
  let { menu } = useSelector((state) => state.menuStore);
  const [navigateMenu, setNavigateMenu] = React.useState(menu);

  const init = async () => {
    const status = await DynamicRouters();
    setIsLoaded(true);
    if (status) {
      navigate(location.pathname === "/login" ? navigateMenu : location.pathname);
    }
  };
  useEffect(() => {
    if (!token) {
      navigate("/login");
    } else {
      init();
    }
  }, [token]);

  useEffect(() => {
    if (isLoaded) {
      if (location.pathname === "/login") {
        navigate(navigateMenu);
      }
    }
  }, [location.pathname, isLoaded]);
  useEffect(() => {
    const path=findFirstPath(menu)
    setNavigateMenu(path)
  },[menu])
  if (!isLoaded && token) {
    return <Spin size="large" />;
  }

  return <div>{children}</div>;
}
